//图书详细页
var router=require('express').Router();
var async=require('async');
var moment=require('moment');
var Book=require('../model/book');
var User=require('../model/user');
var Comment=require('../model/comment');
var History=require('../model/history');
var Favorite=require('../model/favorite');
var reg=require('../lib/reg');

module.exports = router;

router.get('/:sku',(req, res,next)=>{
    var sku=req.params.sku;
    if(!reg.sku(sku))return res.redirect('/');
    Book.findOne({sku:sku},(err,book)=>{
        if(err)return next(err);
        if(!book)return res.redirect('/');

        async.parallel({
            comment:(cb)=>{
                Comment.findOne({_id:book.comment},(err,comment)=>{
                    if(err)return cb(err);
                    if(!comment)return cb({message:'No comment'});
                    comment.badCount=comment.commentCount-(comment.goodCount+comment.generalCount);
                    comment.badRate=1-(comment.goodRate+comment.generalRate);
                    ['goodRate','generalRate','badRate'].forEach((field)=>{
                        comment[field+'Str']=Math.round(comment[field]*100);
                    });
                    cb(null,comment);
                });
            },
            favorite:(cb)=>{
                if(!req.session.user || !req.session.user._id)return cb(null,false);
                Favorite.findOne({sku:sku,user_id:req.session.user._id},{_id:true},(err,doc)=>{
                    if(err)return cb(err);
                    cb(null,doc);
                });
            }
        },(err,ret)=>{
            if(err)return res.redirect('/');
            //console.log('book:',book);
            res.render('item',{title:'《'+book.name+'》',user:req.session.user,book:book,preview:book.previewnames[0],previewnames:book.previewnames,thumbnames:book.thumbnames,comment:ret.comment,favorite:ret.favorite});

            //历史记录
            var user=req.session.user;
            if(!user)return;
            var time=Date.now()-1000*3600*24*(Math.random()*30|0);//模拟从当前时间到之前的30天
            var date=moment(new Date(time)).format('YYYY-MM-DD');
            History.update({user:user._id,book:book._id,userName:user.name,bookTitle:book.name},{date:date},{upsert:true},()=>{});

        });
    });
});